# == Schema Information
#
# Table name: accounts
#
#  id                     :integer          not null, primary key
#  username               :string(255)      default(""), not null
#  email                  :string(255)      default(""), not null
#  encrypted_password     :string(255)      default(""), not null
#  reset_password_token   :string(255)
#  reset_password_sent_at :datetime
#  remember_created_at    :datetime
#  sign_in_count          :integer          default(0)
#  current_sign_in_at     :datetime
#  last_sign_in_at        :datetime
#  current_sign_in_ip     :string(255)
#  last_sign_in_ip        :string(255)
#  confirmation_token     :string(255)
#  confirmed_at           :datetime
#  confirmation_sent_at   :datetime
#  unconfirmed_email      :string(255)
#  created_at             :datetime
#  updated_at             :datetime
#  role                   :string(255)      default("user")
#  blocked                :boolean          default(FALSE)
#

class Account < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable, :async,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :nas, :dependent => :destroy
  has_many :devices, :dependent => :destroy

  validates_presence_of :username, :role
  validates_uniqueness_of :username

  before_create :set_root_role
  def set_root_role
    self.role = 'root' if self.at_root_list?
  end

  def at_root_list?
    Settings.roots.include?(self.email)
  end

  def act_as_root?
    Settings.roots.include?(self.email) && self.role == 'root'
  end

  def act_as_admin?
    self.role == 'admin'
  end

  def act_as_user?
    self.role == 'user'
  end

  def can_manager_site?
    act_as_admin? || act_as_root?
  end

  def not_blocked?
    !self.blocked
  end

  def inactive_message
    not_blocked? ? super : :blocked
  end  

  def active_for_authentication?
    super && not_blocked?
  end
end
